<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 所需组件
echarts.use([
  PieChart,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  CanvasRenderer
]);

// 定义组件 props
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  title: String,
  // color: {
  //   type: Array,
  //   default: () => ['#6a8cff', '#ff6b6b', '#4ecdc4', '#f7fff7', '#ffe66d']
  // }
});

// 定义 ref 用于获取图表容器元素
const chartRef = ref<HTMLElement>();
// 定义 ECharts 实例
let chart: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
  updateChart();
};

// 更新图表配置
const updateChart = () => {
  if (!chart) return;
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '数据',
        type: 'pie',
        radius: '50%',
        data: props.data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        // color: props.color
      }
    ]
  };
  chart.setOption(option);
};

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  // 监听窗口大小变化事件
  window.addEventListener('resize', handleResize);
});

// 监听 props.data 变化，更新图表
watch(() => props.data, updateChart);

onBeforeUnmount(() => {
  chart?.dispose();
  // 移除窗口大小变化事件监听
  window.removeEventListener('resize', handleResize);
});
</script>
